import cx_Oracle

def db_connect(db_param):
    host = "ly_gaxt" if db_param.get('SERVER') is None else db_param.get('SERVER') is None
    port = 1521 if db_param.get('PORT') is None else db_param.get('PORT')
    dbname = 'orcl' if db_param['DBNAME'] is None else db_param['DBNAME']
    pwd = db_param['PWD']
    username = db_param['USER']
    dsn = cx_Oracle.makedsn(host, port, dbname)
    db = cx_Oracle.connect(username, pwd, dsn)
    print("connect to oracle success, version %s" % db.version)
    return db


def db_disconnect(db):
    if db is not None:
        db.close()
        db = None
    return db


def db_select(db, sql, param, is_dict=False):
    """
    查询多行，参数允许使用元组或字典，默认返回元组格式可设置成返回字典结构
    :param db: 数据库连接对象
    :param sql: SQL
    :param param: 参数
    :param is_dict: 是否使用字典结构
    :return:
    """
    cur = db.cursor()
    cur.execute(sql, param)
    rows = cur.fetchall()
    if is_dict is False:
        cur.close()
        return rows
    cols = [d[0] for d in cur.description]
    result = []
    for row in rows:
        result.append(dict(zip(cols, row)))
    cur.close()
    return result


def db_select_one(db, sql, param, is_dict=False):
    cur = db.cursor()
    cur.execute(sql, param)
    row = cur.fetchone()
    if is_dict is False:
        cur.close()
        return row
    cols = [d[0] for d in cur.description]
    cur.close()
    return None if row is None else dict(zip(cols, row))
